﻿//文档就绪函数
$(function () {
    //初始化表格
    ShwoAllocate();
});

var token = localStorage.getItem("token");

//调拨列表展示
function ShwoAllocate() {
    layui.use(function () {
        var table = layui.table;
        var AllocateNumber = $("#AllocateNumber").val();
        var AllocateDate = $("#AllocateDate").val();
        var AllocateStatus = $("#AllocateStatus").val();

        // 点击导出按钮
        document.getElementById('exportBtn').addEventListener('click', function () {
            var checkStatus = table.checkStatus('AllocateTable');  // 获取当前表格的选中状态
            var selectedData = checkStatus.data;  // 获取选中的数据
            if (selectedData.length === 0) {
                alert('请先选择要导出的数据!');
                return;
            }
            var filteredData = selectedData.map(function (item) {
                // 创建一个新对象，只包含您想要的属性
                return {
                    '调拨编号': item.allocateNumber,
                    '调拨日期': item.allocateDate,
                    '仓库编码': item.warehouseNo,
                    '原料编码': item.ingredientnumber,
                    '原料名称': item.ingredientName,
                    '原料批次号': item.ingredientBatchNum,
                    '调拨数量': item.allocateNum,
                    '调拨人': item.allocatePerson,
                    '状态': item.allocateStatus,
                };
            });
            console.log(filteredData);

            // 使用 XLSX 导出选中的数据
            var wb = XLSX.utils.book_new();
            var ws = XLSX.utils.json_to_sheet(filteredData); // 将选中的数据转换为工作表
            XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

            // 导出为 Excel 文件
            XLSX.writeFile(wb, '调拨列表.xlsx');
        });

        //执行渲染
        table.render({
            elem: '#AllocateTable',
            page: {
                limit: 15, //每页显示的条数
                limits: [15, 20, 25, 30] //每页显示条数的选择项
            },
            cols: [[
                { type: 'checkbox', fixed: 'left' },
                { field: 'allocateNumber', title: '调拨编号', width: 150 },
                { field: 'allocateDate', title: '调拨日期', width: 160 },
                //{ field: 'warehouseNo', title: '仓库编码', width: 130 },
                //{ field: 'ingredientnumber', title: '原料编码', width: 130 },
                //{ field: 'ingredientName', title: '原料名称', width: 130 },
                //{ field: 'ingredientBatchNum', title: '原料批次号', width: 130 },
                //{ field: 'allocateNum', title: '调拨数量', width: 130 },
                { field: 'allocateNum', title: '调拨数量', width: 130 },
                { field: 'reviewer', title: '调拨人', width: 130 },
                {
                    field: 'allocateStatus', title: '状态', width: 130,
                    templet: function (d) {
                        // 根据状态返回不同颜色的字体
                        var statusColor = '';
                        switch (d.allocateStatus) {
                            case '待审核':
                                statusColor = 'style="color: #ffb800;"';
                                break;
                            case '审核中':
                                statusColor = 'style="color: #31bdec;"';
                                break;
                            case '已通过':
                                statusColor = 'style="color: #16b777;"';
                                break;
                            case '已驳回':
                                statusColor = 'style="color: #ff5722;"';
                                break;
                            default:
                                // 如果状态不是上述任何一个，可以使用默认颜色或不做特殊处理
                                statusColor = '';
                        }
                        // 返回带有样式的状态文本
                        return '<span ' + statusColor + '>' + d.allocateStatus + '</span>';
                    }
                },
                {
                    field: '', title: '操作', width: 240, templet: function (d) {

                        return '<a class="layui-btn layui-bg-blue layui-btn-xs" onclick="Examine(' + d.allocateId + ')">审核</a>' +
                            '<a class="layui-btn layui-bg-blue layui-btn-xs" onclick="CheckInfo(' + d.allocateId + ')">查看</a>' +
                            '<a class="layui-btn layui-bg-blue layui-btn-xs"  onclick="EditAllocate(' + d.allocateId + ')"  >编辑</a>' +
                            '<a class="layui-btn layui-bg-red layui-btn-xs" layui-bg-red onclick="DeleteWWHours(' + d.allocateId + ')">删除</a>';
                    },
                }
            ]],
            //数据接口
            data: []
        });
        //请求数据
        $.ajax({
            url: '../Allocate/GetAllocateList',
            type: "get",
            headers: {
                "Authorization": token
            },
            data: {
                PageIndex: 1,
                PageSize: 15,
                AllocateNumber: AllocateNumber,
                AllocateDate: AllocateDate,
                AllocateStatus: AllocateStatus
            },
            success: function (data) {
                data = JSON.parse(data);
                //console.log(data);
                table.reload('AllocateTable', {
                    page: {
                        limit: 15,
                        limits: [15, 20, 25, 30]
                    },
                    data: data.data.list
                });
            },
            error: function () {
                console.log("请求失败");
            }

        });
    })
}

var obj = {
    WorkerListId: '',
    WorkerNumber: '',
    WorkersName: '',
    PhoneNumber: '',
    Gender: '',
    Department: '',
    TeamsAndGroups: '',
    Status: ''
};

//审核
function Examine(allocateId) {
    var table = layui.table;
    var form = layui.form;
    var layer = layui.layer;
    layer.open({
        type: 1,
        title: '审核操作',
        area: ['400px', '200px'], // 弹出框的宽高
        content: `
            <div class="layui-form">
                <div class="layui-form-item">
                    <label class="layui-form-label">选择操作</label>
                    <div class="layui-form">
                      <input type="radio" name="allocateStatus" value="通过" title="通过">
                      <input type="radio" name="allocateStatus" value="审核中" title="审核中">
                      <input type="radio" name="allocateStatus" value="驳回" title="驳回">
                    </div>
                </div>

                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button type="button" class="layui-btn" onclick="submitAction('${allocateId}')">确定</button>
                        <button type="button" class="layui-btn layui-btn-primary" onclick="layer.closeAll();">取消</button>
                    </div>
                </div>
            </div>`,
        success: function () {
            // 确保DOM元素已完全加载后渲染表单
            setTimeout(function () {
                form.render();
            }, 300); // 使用 setTimeout 延迟渲染，确保DOM完全加载
        }
    });
}

function submitAction(allocateId) {
    var formElem = document.querySelector('.layui-layer-content .layui-form');
    var radios = formElem.querySelectorAll('input[name="allocateStatus"]:checked');
    var action = radios.length > 0 ? radios[0].value : null;

    if (action) {
        $.ajax({
            url: '../Allocate/UpdateAllocateStatus',
            type: 'Post',
            headers: {
                "Authorization": token
            },
            data: {
                AllocateId: allocateId,
                AllocateStatus: action
            },
            success: function (response) {
                console.log(res);
                if (res.code === 1) {
                    layer.alert("更新成功", { icon: 1 });
                    setTimeout(function () {
                        // 刷新页面
                        ShwoAllocate();
                        layer.closeAll();
                    }, 2000);
                } else {
                    layer.alert("更新失败", { icon: 2 });
                }
            },
            error: function () {
                layer.msg('请求失败，请稍后再试', { icon: 2 });
            }
        });
    } else {
        layer.msg('请选择一个操作', { icon: 2 });
    }
}

//查看
layui.use(['table', 'form', 'layer'], function () {
    var table = layui.table;
    var form = layui.form;
    var layer = layui.layer;
    //查看调拨信息
    window.CheckInfo = function (allocateId) {
        var token = localStorage.getItem("token");
        //先根据id获取数据
        $.ajax({
            type: "Get",
            headers: {
                "Authorization": token
            },
            url: "/Allocate/ReverseAllocate",
            data: { AllocateId: allocateId },
            success: function (res) {
                const reponse = JSON.parse(res);
                console.log(reponse.data);
                const find = reponse.data;
                $("#AllocateNumberCheck").val(find.allocateNumber);
                $("#AllocateNum").val(find.allocateNum);
                $("#AllocateDateCheck").val(find.allocateDate);
                $("#AllocatePerson").val(find.allocatePerson);
                $("#AllocateReason").val(find.allocateReason);
                $("#Notes").val(find.notes);
                $("#Associate").val(find.associate);
                $("#Transport").val(find.transport);
                // 重新渲染所有表单元素
                layui.form.render();
            }
        });
        layer.open({
            type: 1,//iframe层
            title: '查看调拨信息',
            shadeClose: true,  // 点击遮罩区域，关闭弹层
            shade: 0.8,//遮罩透明度
            area: ['700px', '500px'],//弹层大小
            anim: 0, // 0-6 的动画形式，-1 不开启
            content: `<form class="layui-form">
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">调拨编号:</label>
                <div class="layui-input-inline">
                    <input type="text" id="AllocateNumberCheck" name="AllocateNumberCheck" required lay-verify="required"disabled lay-verify="required" autocomplete="off" class="layui-input" disabled>
                </div>
            </div>

            <div class="layui-inline">
                <label class="layui-form-label">调拨数量:</label>
                <div class="layui-input-inline">
                    <input type="number" lay-affix="number" id="AllocateNum" name="AllocateNum" required lay-verify="required" disabled min="1" class="layui-input">
                </div>
            </div>
        </div>

        <div class="layui-form-item">

        <div class="layui-inline">
          <label class="layui-form-label">调拨日期</label>
          <div class="layui-input-inline">
            <input type="text" class="layui-input" id="AllocateDateCheck" name="AllocateDate" required lay-verify="required" disabled>
          </div>
        </div>
            <div class="layui-inline">
                <label class="layui-form-label">调拨人:</label>
                <div class="layui-input-inline">
                    <input type="text" id="AllocatePerson" name="AllocatePerson" required lay-verify="required" disabled lay-verify="required"   autocomplete="off" class="layui-input">
                </div>
            </div>
        </div>

            <div class="layui-form-item">

            <div class="layui-inline">
                <label class="layui-form-label">调拨原因:</label>
                <div class="layui-input-inline">
                    <textarea id="AllocateReason" name="AllocateReason" required lay-verify="required" disabled class="layui-textarea"></  textarea>
                </div>
            </div>

            <div class="layui-inline">
                <label class="layui-form-label">备注:</label>
                <div class="layui-input-inline">
                    <textarea id="Notes" name="Notes" disabled required lay-verify="required" class="layui-textarea"></textarea>
                </div>
            </div>
        </div>

        <div class="layui-form-item">

            <div class="layui-inline">
                <label class="layui-form-label">关联生产订单:</label>
                <div class="layui-input-inline">
                    <div class="layui-input-inline">
                    <input type="text" id="Associate" name="Associate" required lay-verify="required" disabled lay-verify="required" autocomplete="off" class="layui-input">
                </div>
                </div> 
            </div>

            <div class="layui-inline">
                <label class="layui-form-label">运输方式:</label>
                <div class="layui-input-inline">
                   <select id="Transport" name="Transport" lay-filter="Transport">
                      <option value="">请选择运输方式</option>
                      <option value="传送带">传送带</option>
                      <option value="叉车">叉车</option>
                   </select>
                </div>
            </div>
        </div>
        </form>`,
            success: function () {
                // 确保DOM元素已完全加载后渲染表单
                setTimeout(function () {
                    form.render();
                }, 300); // 使用 setTimeout 延迟渲染，确保DOM完全加载
            }
        });
    }
});

//删除工人工时
window.DeleteWWHours = function (id) {
    var token = localStorage.getItem("token");
    var data = JSON.stringify({
        wwHoursId: id,
        deletedBy: "张三"
    })
    layer.confirm('确定要删除该数据吗？', function (index) {
        $.ajax({
            url: '../WWHours/DeleteWWHours',
            type: "Post",
            headers: {
                "Authorization": token
            },
            data: { data: data },
            success: function (res) {
                console.log(res);
                var res = JSON.parse(res);
                if (res.code === 1) {
                    layer.msg('删除成功', { icon: 1 });
                    ShwoAllocate();
                } else {
                    layer.msg('删除失败', { icon: 2 });
                }
            },
            error: function () {
                layer.msg('删除失败,请稍后重试', {
                    time: 2000,
                    icon: 2
                });
            }
        });
        layer.close(index);
    });
}

//编辑调拨信息
//跳转到编辑页面
function EditAllocate(allocateId) {
    localStorage["allocateId"] = allocateId;
    window.location.href = "/Allocate/EditAllocate";
}
